package com.studyroom.controller;

import com.studyroom.common.Result;
import com.studyroom.dto.LoginDTO;
import com.studyroom.dto.RegisterDTO;
import com.studyroom.dto.VerifyIdentityDTO;
import com.studyroom.dto.ResetPasswordDTO;
import com.studyroom.entity.User;
import com.studyroom.service.UserService;
import com.studyroom.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import lombok.Data;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping("/login")
    public Result<String> login(@RequestBody LoginDTO loginDTO) {
        String token = userService.login(loginDTO);
        return Result.success(token);
    }

    @GetMapping("/userinfo")
    public Result<User> getUserInfo(@RequestHeader("Authorization") String token) {
        if (token != null && token.startsWith("Bearer ")) {
            String jwt = token.substring(7);
            String username = jwtTokenUtil.extractUsername(jwt);
            User user = userService.getUserByUsername(username);
            if (user != null) {
                // 清除敏感信息
                user.setPassword(null);
                return Result.success(user);
            }
        }
        return Result.error("获取用户信息失败");
    }

    @PostMapping("/register")
    public Result<?> register(@RequestBody RegisterDTO registerDTO) {
        userService.register(registerDTO);
        return Result.success();
    }

    // 验证身份
    @PostMapping("/verify-identity")
    public Result<?> verifyIdentity(@RequestBody VerifyIdentityDTO dto) {
        log.info("验证身份: {}", dto);
        
        User user = userService.findByUsernameAndPhone(dto.getUsername(), dto.getPhone());
        
        if (user == null) {
            return Result.error("用户名或手机号不匹配");
        }
        
        return Result.success(new VerifyResult(user.getId()));
    }

    // 重置密码
    @PostMapping("/reset-password") 
    public Result<?> resetPassword(@RequestBody ResetPasswordDTO dto) {
        log.info("重置密码: userId={}", dto.getUserId());
        
        User user = userService.getById(dto.getUserId());
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        // 检查新密码是否与旧密码相同
        if (dto.getPassword().equals(user.getPassword())) {
            return Result.error(400, "新密码不能与旧密码相同");
        }
        
        // 更新密码(明文存储)
        user.setPassword(dto.getPassword());
        userService.updateById(user);
        
        return Result.success("密码重置成功");
    }
    
    @Data
    @AllArgsConstructor
    private static class VerifyResult {
        private Long userId;
    }
} 